﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Jayden.Dll.Web.HtmlControls.Generics;
using Jayden.Dll.Core.Extensions;

namespace Jayden.Dll.Web.Helper
{
	public class DesignerHelper
	{
		public StringBuilder BuildDesignerFromXmlDocument(XmlDocument document, HtmlControlLoader loader)
		{
			XmlNodeList list = document.SelectNodes("//*[@data-server-id]");
			List<XmlElement> ids = new List<XmlElement>();
			foreach (XmlNode node in list)
			{
				if (node is XmlElement)
				{
					XmlElement element = node as XmlElement;
					ids.Add(element);
				}
			}
			StringBuilder declarationBuilder = new StringBuilder();
			StringBuilder loadBuilder = new StringBuilder();
			loadBuilder.AppendLine("\t\tpublic override void Load(XmlNode node, HtmlControlLoader loader)");
			loadBuilder.AppendLine("\t\t{");
			loadBuilder.AppendLine("\t\t\tbase.Load(node, loader);");
			foreach (XmlElement id in ids)
			{
				Type type = HtmlControl.GetType(id.Name, loader);
				string typeName = type.Name;
				string dataServerId = id.Attributes["data-server-id"].Value;
				string memberName = "m_" + dataServerId.ToUpperFirst();
				declarationBuilder.AppendLine(string.Format("\t\tprotected {0} {1};", typeName, memberName));
				loadBuilder.AppendLine(string.Format("\t\t\t{0} = GetElementByServerId<{1}>(\"{2}\");", memberName, typeName, dataServerId));
			}
			loadBuilder.AppendLine("\t\t}");
			declarationBuilder.Append(loadBuilder);
			return declarationBuilder;
		}
	}
}
